const CryptoJS = require('crypto-js');
export function spawnKey(code) {
  // 生成16位16进制密钥
  var check_dec = '';
  // 获取本地时间
  var timestamp = new Date();
  // console.log(timestamp.toLocaleString());
  // 验证码转ascii拼接
  for (const key in code) {
    var asc_code = code[key].charCodeAt();
    check_dec += asc_code;
  }
  // 生成验证码部分16进制字符串
  var hex_code = Number(check_dec).toString(16);
  // 获取分秒
  var min = timestamp.getMinutes().toString();
  var sec = timestamp.getSeconds().toString();
  // 补0
  if (sec.length == 1) {
    sec = '0'+sec;
  }
  if (min.length == 1) {
    min = '0'+min;
  }
  // 分秒拼接
  var time_num = min + sec;
  // console.log(time_num,'pass');
  // 分秒转换16位
  var hex = Number(time_num).toString(16);
  // console.log(hex,'time');
  var pass_code = hex_code + hex;
  // console.log(pass_code,'finial',16 - pass_code.length,'times');
  // 缓存随机生成部分
  var rand_part = '';
  for (;16 - pass_code.length >0;) {
    var rand_num = Math.round(Math.random()*5 +10);
    var rand_hex = rand_num.toString(16);
    rand_part += rand_hex;
    pass_code += rand_hex;
    // console.log('rand_spawn',rand_num,rand_hex);
  }
  // console.log(pass_code,'res');
  return [pass_code,rand_part,timestamp.toLocaleString()]
}

export function Encrypt(se_key,word){
  // 生成偏移量
  let sha256_iv = CryptoJS.SHA256(se_key).toString();
  let iv_str = sha256_iv.substring(0, 16); // 截取16位
  const key = CryptoJS.enc.Utf8.parse(se_key);
  const iv = CryptoJS.enc.Utf8.parse(iv_str);
  const bytes = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(bytes, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.ciphertext.toString();
}

export function infoEncode(secret_key,word){
  var hash_word  = CryptoJS.SHA256(word).toString();
  return Encrypt(secret_key, hash_word);
}